<?php

if (php_sapi_name() == 'cli-server' && !empty($_SERVER['REQUEST_URI'])) {
    $qstPos = strpos($_SERVER['REQUEST_URI'], '?');
    $path = '';
    if ($qstPos === false) {
        $path = $_SERVER['REQUEST_URI'];
    } elseif ($qstPos > 0) {
        $path = substr($_SERVER['REQUEST_URI'], 0, $qstPos);
    }
    if ($path) {
        if (preg_match('/\.(?:png|jpg|jpeg|gif|js|json|css|woff|woff2|ttf)$/', $path)) {
            return false;
        }
    }
    unset($qstPos);
    unset($path);
}

// phpinfo(); return;

/**
 * 将变量限制在局部
 */
function _main()
{
    define('BASE_DIR', realpath(__DIR__ . '/..'));

    /** @var \Composer\Autoload\ClassLoader $loader */
    $loader = require BASE_DIR . '/vendor/autoload.php';
    $loader->addPsr4('Wgx\\Admin\\', BASE_DIR);

    \PhpYes\Apps::$p = \PhpYes\Apps::getSingle(\Wgx\Admin\Test\App::class);

    \PhpYes\Modules\Log\LoggerManager::init(\PhpYes\Apps::getConfig('log.php'));
    \Wgx\PdoEx\PdoManager::init(\PhpYes\Apps::getConfig('pdo.php'), new \Wgx\Admin\Test\DbConfig());
    \PhpYes\Com\RedisManager::init(\PhpYes\Apps::getConfig('redis.php'));

    try {
        \Wgx\Admin\Com\AdminSession::init();

        $router = \PhpYes\Apps::router();
        $router->route(\PhpYes\Apps::getReqMethod(), \PhpYes\Apps::getReqPath());
        $class = $router->class;
        $func = $router->function;
        $obj = new $class();
        if (method_exists($obj, 'preflight')) {
            $obj->preflight($app);
        }
        $obj->$func($app);
    } catch (\Exception $e) {
        // 这里要根据实际情况来渲染
        if ($e instanceof \Wgx\Admin\Com\NotLoginException) {
            if (\PhpYes\Apps::isXMLHttpRequest()) {
                \PhpYes\Apps::render()->returnJsonWithErrorMessage($e->getMessage(), 430);
            } else {
                \PhpYes\Apps::render()->redirect('/adminuser/login?referer=' . urlencode($_SERVER['REQUEST_URI']));
            }
        } elseif ($e instanceof \Wgx\Admin\Com\NoMenuRightException) {
            if (\PhpYes\Apps::isXMLHttpRequest()) {
                \PhpYes\Apps::render()->returnJsonWithErrorMessage($e->getMessage(), 431);
            } else {
                \PhpYes\Apps::render()->displayError($e->getMessage(), 431);
            }
        } elseif ($e instanceof \Wgx\Admin\Com\Crud\InvalidFieldValueException) {
            if (\PhpYes\Apps::isXMLHttpRequest()) {
                \PhpYes\Apps::render()->returnJson(array('code' => 432, 'field' => $e->getFieldName(), 'msg' => $e->getMessage()));
            } else {
                // 使用通用错误页面，如有必须，可以单独设计一个专用错误页面
                \PhpYes\Apps::render()->displayError($e->getFieldName() . ' => ' . $e->getMessage(), 432);
            }
        } elseif ($e instanceof \PhpYes\Com\HttpException) {
            // 这种异常体系(即HttpException以及它的子类)下的异常我们认为是可以展示给用户看的
            \PhpYes\Modules\Log\Example\AppLogHelper::logException($e);
            if (\PhpYes\Apps::isXMLHttpRequest()) {
                \PhpYes\Apps::render()->returnJsonWithErrorMessage($e->getMessage(), $e->getHttpRspCode());
            } else {
                \PhpYes\Apps::render()->displayError($e->getMessage(), $e->getHttpRspCode());
            }
        } else {
            // 这种不知道类型的异常不能展示给用户，以防异常中有敏感数据
            \PhpYes\Modules\Log\Example\AppLogHelper::logException($e);
            if ($env == \PhpYes\AppsProxy::ENVProduction) {
                $errMsg = '服务器错误，请稍后重试!';
                if (\PhpYes\Apps::isXMLHttpRequest()) {
                    \PhpYes\Apps::render()->returnJsonWithErrorMessage($errMsg, 500);
                } else {
                    \PhpYes\Apps::render()->display5xx($errMsg, 500);
                }
            } else { // 非生产环境的话，那么一般就是开发或者测试环境了，这种情况下直接抛出异常以便渲染出来给开发或者测试人员查看，以便定位问题
                throw $e;
            }
        }
    }
}

_main();
